package com.dabai.qrtools;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.dabai.qrtools.other.MainUtils;
import com.dabai.qrtools.qrcode.QRCodeUtils;
import com.dabai.qrtools.ui.BatchGenerateActivity;
import com.dabai.qrtools.ui.ContactQrActivity;
import com.dabai.qrtools.ui.GenerateActivity;
import com.dabai.qrtools.ui.MoreActivity;
import com.dabai.qrtools.ui.ResultActivity;
import com.dabai.qrtools.ui.SettingsActivity;
import com.dabai.qrtools.utils.ActivityUtils;
import com.dabai.qrtools.utils.AppUtils;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.SharedPreferencesUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.zxing.activity.CaptureActivity;
import com.google.zxing.util.Constant;
import com.permissionx.guolindev.PermissionX;

public class MainActivity extends AppCompatActivity {

    Context context;
    private MaterialToolbar mToolbar;
    private CardView mGenerate;
    private CardView mScanner;
    private CardView mGetclip;
    private CardView mContact;
    private CardView mListqr;
    private CardView mWifiqr;
    private CardView mSetting;
    private CardView mMore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();

        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);

        initListenerEvent();

        MainUtils.permissionToApplyFor(this);

    }

    /**
     * 初始化事件侦听器
     */
    private void initListenerEvent() {

        mGenerate.setOnClickListener(view -> {
            ActivityUtils.startActivity(context, GenerateActivity.class);
        });
        mGenerate.setOnLongClickListener(v -> {
            MainUtils.showGenerateHistory(context);
            return true;
        });

        mContact.setOnClickListener(view -> {
            ActivityUtils.startActivity(context, ContactQrActivity.class);
        });

        mScanner.setOnClickListener(view -> {

            if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("oldVersionScan",false)){
                PermissionX.init(this)
                        .permissions(Manifest.permission.CAMERA)
                        .request((allGranted, grantedList, deniedList) -> {
                            if (!allGranted) {
                                DabaiUtils.showToast(context, "需要拍照权限");
                            } else {
                                ActivityUtils.startActivityForResult(this, CaptureActivity.class, 201);
                            }
                        });
            }else {
                QRCodeUtils.startQrCodeScanner(this, 101);
            }


        });
        mScanner.setOnLongClickListener(v -> {
            MainUtils.showScanHistory(context);
            return true;
        });

        mGetclip.setOnClickListener(view -> {

            MainUtils.toGenerateQr(context, DabaiUtils.getClipboardContent(context));

        });

        mWifiqr.setOnClickListener(v -> {
            if (AppUtils.isAppInstalled(context, "com.dabai.wifiseepass")) {
                AppUtils.openApp(context, "com.dabai.wifiseepass");
            } else {
                DabaiUtils.openLink(context, "https://www.coolapk.com/apk/com.dabai.wifiseepass");
            }
        });

        mListqr.setOnClickListener(v -> {
            ActivityUtils.startActivity(context, BatchGenerateActivity.class);
        });
        mMore.setOnClickListener(v -> {
            ActivityUtils.startActivity(context, MoreActivity.class);
        });
        mSetting.setOnClickListener(v -> {
            ActivityUtils.startActivity(context, SettingsActivity.class);
        });
        mSetting.setOnLongClickListener(v -> {
            DabaiUtils.toMyAppInfo(context);
            return true;
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 101) {
                if (data != null) {

                    String result = QRCodeUtils.getQrCodeScannerResult(data);
                    MainUtils.toScanQr(context, result);

                }
            }
            if (requestCode == 201) {
                if (data != null) {

                    String content = data.getStringExtra(Constant.INTENT_EXTRA_KEY_QR_SCAN);
                    MainUtils.toScanQr(context,content);

                }
            }
        }

    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                DabaiUtils.showToast(context, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mGenerate = findViewById(R.id.generate);
        mScanner = findViewById(R.id.scanner);
        mGetclip = findViewById(R.id.getClip);
        mContact = findViewById(R.id.contact);
        mListqr = findViewById(R.id.listQr);
        mWifiqr = findViewById(R.id.wifiQr);
        mSetting = findViewById(R.id.setting);
        mMore = findViewById(R.id.more);
    }
}